<template>
  <div>
    <el-dialog :title="titleStr" :visible.sync="data.bSwitch" width="940px">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="180px"
        class="demo-ruleForm"
        v-loading="uploadLoading"
      >
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="名称" prop="name">
              <el-input
                v-model="ruleForm.name"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input
                v-model="ruleForm.description"
                placeholder="请输入描述"
                style="width: 100%"
                type="textarea"
                :rows="3"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属地" prop="ownType">
              <el-select
                v-model="ruleForm.ownType"
                clearable
                filterable
                placeholder="请选择"
                style="width: 218px"
              >
                <el-option
                  v-for="dict in dict.type.template_own_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="catType">
              <el-select
                v-model="ruleForm.catType"
                clearable
                filterable
                placeholder="请选择"
                style="width: 218px"
              >
                <el-option
                  v-for="dict in dict.type.template_cat_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人群" prop="userType">
              <el-select
                v-model="ruleForm.userType"
                clearable
                filterable
                placeholder="请选择"
                style="width: 218px"
              >
                <el-option
                  v-for="dict in dict.type.template_user_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="userSex">
              <el-radio-group v-model="ruleForm.userSex">
                <el-radio label="0">男</el-radio>
                <el-radio label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格（元）" prop="price">
              <el-input-number
                v-model="ruleForm.price"
                :precision="2"
                controls-position="right"
                :min="0"
                :step="1"
                placeholder="请输入"
                style="width: 218px"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用数量" prop="usedNum">
              <el-input-number
                v-model="ruleForm.usedNum"
                controls-position="right"
                :min="0"
                :step="1"
                step-strictly
                placeholder="请输入"
                style="width: 218px"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权重" prop="weight">
              <el-input-number
                v-model="ruleForm.weight"
                controls-position="right"
                :min="0"
                :step="1"
                step-strictly
                style="width: 218px"
                placeholder="请输入"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面" prop="coverUrl">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="uploadRequest"
              >
                <img
                  v-if="ruleForm.coverUrl"
                  :src="ruleForm.coverUrl"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="示例照片" prop="files">
              <el-upload
                class="avatar-uploader"
                action="#"
                list-type="picture-card"
                :before-upload="beforeAvatarUpload"
                :http-request="uploadRequestFiles"
                multiple
                :on-exceed="handleOverLimit"
                :limit="5"
                :file-list="ruleForm.files"
                :on-change="handFileChange"
              >
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{ file }">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg、png文件，且不超过20M
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="示例视频" prop="video">
              <el-upload
                class="upload-demo"
                action="#"
                :before-upload="beforeVideoUpload"
                :http-request="uploadRequestVideo"
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="videoList"
                :on-remove="handleVideoRemove"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传mp4文件，且不超过20M
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
					
          <el-col :span="24" v-if="videoList.length">
            <el-form-item label="视频封面" prop="movieThumbnailUrl">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="uploadMovieThumbnailRequest"
              >
                <img
                  v-if="ruleForm.movieThumbnailUrl"
                  :src="ruleForm.movieThumbnailUrl"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="videoList.length">
            <el-form-item
              label="1图片1视频价格（元）"
              prop="moviePrice"
              label-width="180px"
            >
              <el-input-number
                v-model="ruleForm.moviePrice"
                :precision="2"
                controls-position="right"
                :min="0"
                :step="1"
                placeholder="请输入"
                style="width: 218px"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="AI提示词" prop="prompt">
              <el-input
                v-model="ruleForm.prompt"
                placeholder="请输入"
                style="width: 218px"
                type="textarea"
                :rows="3"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="ruleForm.status"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="创建人" prop="remark">
              <el-input
                type="input"
                v-model="ruleForm.remark"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="data.bSwitch = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="uploadLoading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 预览图片 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { addTemplate, getTemplate, updateTemplate } from "@/api/template";
import { uploadImgTencent } from "@/api/banner";

export default {
  props: {
    data: {
      type: Object,
      default() {
        return {
          id: null,
          bSwitch: false,
        };
      },
    },
  },
  dicts: ["template_cat_type", "template_own_type", "template_user_type"],
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      ruleForm: {
        name: null,
        description: null,
        weight: undefined,
        status: 0,
        coverUrl: null,
        ownType: null,
        catType: null,
        userType: null,
        userSex: "1",
        price: 29.9,
        usedNum: 999999,
        remark: null,
        prompt: null,
        files: [],
				moviePrice: undefined,
				movieThumbnailUrl: null
      },
      videoList: [],
      selectFileCount: 0,
      uploadLoading: false,
      rules: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        description: [{ required: false, message: "请输入", trigger: "blur" }],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        ownType: [{ required: true, message: "请选择", trigger: "change" }],
        catType: [{ required: true, message: "请选择", trigger: "change" }],
        userType: [{ required: true, message: "请选择", trigger: "change" }],
        price: [{ required: true, message: "请输入", trigger: "blur" }],
        usedNum: [{ required: true, message: "请输入", trigger: "blur" }],
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        coverUrl: [{ required: true, message: "请上传", trigger: "change" }],
        files: [{ required: true, message: "请上传", trigger: "change" }],
        moviePrice: [{ required: true, message: "请输入", trigger: "blur" }],
				movieThumbnailUrl: [{ required: true, message: "请上传", trigger: "change" }],
      },
    };
  },
  computed: {
    titleStr() {
      return this.data.id ? "修改" : "新增";
    },
  },
  created() {
    this.data.id && this.getDetail();
  },
  methods: {
		// 视频封面
    uploadMovieThumbnailRequest(file) {
      const { name, size } = file.file;
      const preanme = name.split(".")[0];
      const ext = name.replace(preanme, "");
      try {
        uploadImgTencent({ name, size, ext, type: 0, file: file.file }).then(
          (res) => {
            const { code } = res;
            if (code === 200) {
              this.ruleForm.movieThumbnailUrl = res.file.url;
              this.uploadLoading = false;
            } else {
              return Promise.reject();
            }
          }
        );
      } catch (error) {
        return Promise.reject();
      }
    },
		// 视频
    beforeVideoUpload(file) {
      const isType = ["video/mp4"].includes(file.type);
      const isLt20M = file.size / 1024 / 1024 < 20;

      if (!isType) {
        this.$message.error("上传视频只能是 MP4 格式!");
      }
      if (!isLt20M) {
        this.$message.error("上传头像图片大小不能超过 20MB!");
      }
      if (isType && isLt20M) {
        this.uploadLoading = true;
      }
      return isType && isLt20M;
    },
    handleVideoRemove() {
      this.$set(this, "videoList", []);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传1个视频`);
    },
    // 上传示例文件请求
    uploadRequestVideo(file) {
      const { name, size } = file.file;
      const preanme = name.split(".")[0];
      const ext = name.replace(preanme, "");
      this.uploadLoading = true;
      try {
        uploadImgTencent({ name, size, ext, type: 0, file: file.file }).then(
          (res) => {
            const { code } = res;
            if (code === 200) {
              this.videoList.push(res.file);
            } else {
              return Promise.reject();
            }
            this.uploadLoading = false;
          }
        );
      } catch (error) {
        return Promise.reject();
      }
    },
    beforeAvatarUpload(file) {
      const isType = ["image/png", "image/jpeg"].includes(file.type);
      const isLt20M = file.size / 1024 / 1024 < 10;

      if (!isType) {
        this.$message.error("上传头像图片只能是 JPG或PNG 格式!");
      }
      if (!isLt20M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      if (isType && isLt20M) {
        this.uploadLoading = true;
      }
      return isType && isLt20M;
    },
    // 上传封面请求
    uploadRequest(file) {
      const { name, size } = file.file;
      const preanme = name.split(".")[0];
      const ext = name.replace(preanme, "");
      try {
        uploadImgTencent({ name, size, ext, type: 0, file: file.file }).then(
          (res) => {
            const { code } = res;
            if (code === 200) {
              this.ruleForm.coverUrl = res.file.url;
              this.uploadLoading = false;
            } else {
              return Promise.reject();
            }
          }
        );
      } catch (error) {
        return Promise.reject();
      }
    },
    // 上传示例文件请求
    uploadRequestFiles(file) {
      const { name, size } = file.file;
      const preanme = name.split(".")[0];
      const ext = name.replace(preanme, "");

      try {
        uploadImgTencent({ name, size, ext, type: 0, file: file.file }).then(
          (res) => {
            const { code } = res;
            if (code === 200) {
              this.ruleForm.files.push(res.file);
              if (this.ruleForm.files.length === this.selectFileCount) {
                this.uploadLoading = false;
              }
            } else {
              return Promise.reject();
            }
          }
        );
      } catch (error) {
        return Promise.reject();
      }
    },
    // 文件个数超出范围
    handleOverLimit(files, fileList) {
      this.$modal.msgWarning(`最多上传${fileList.length}张图片`);
    },
    handFileChange(file, fileList) {
      this.selectFileCount = fileList.length;
    },
    // 删除图片
    handleRemove(file) {
      const index = this.ruleForm.files.findIndex(
        (item) => item.uuid === file.uuid
      );
      this.ruleForm.files.splice(index, 1);
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 获取详情
    getDetail() {
      getTemplate(this.data.id).then((res) => {
        const {
          name,
          description,
          weight,
          status,
          coverUrl,
          ownType,
          catType,
          userType,
          price,
          usedNum,
          remark,
          prompt,
          files,
          userSex,
          moviePrice,
					movieThumbnailUrl,
					movieInfo
        } = res.data;
        this.$set(this.ruleForm, "name", name);
        this.$set(this.ruleForm, "description", description);
        this.$set(this.ruleForm, "weight", weight ? weight : undefined);
        this.$set(this.ruleForm, "status", status);
        this.$set(this.ruleForm, "coverUrl", coverUrl);
        this.$set(this.ruleForm, "ownType", ownType);
        this.$set(this.ruleForm, "catType", catType);
        this.$set(this.ruleForm, "userType", userType);
        this.$set(this.ruleForm, "userSex", userSex);
        this.$set(this.ruleForm, "usedNum", usedNum);
        this.$set(this.ruleForm, "remark", remark);
        this.$set(this.ruleForm, "prompt", prompt);
        this.$set(this.ruleForm, "price", price / 100);
        this.$set(this.ruleForm, "files", files);
				if (movieInfo.uuid) {
        	this.$set(this, "videoList", [movieInfo]);
        	this.$set(this.ruleForm, "movieThumbnailUrl", movieThumbnailUrl);
        	this.$set(this.ruleForm, "moviePrice", moviePrice / 100);
				}
      });
    },
    // 提交
    onSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          const {
            name,
            description,
            weight,
            status,
            coverUrl,
            ownType,
            catType,
            userType,
            price,
            usedNum,
            remark,
            prompt,
            files,
            userSex,
            moviePrice,
						movieThumbnailUrl
          } = this.ruleForm;
          const params = {
            name,
            description,
            weight,
            coverUrl,
            ownType,
            catType,
            userType,
            userSex,
            price: price * 100,
            usedNum,
            remark,
            prompt,
            files,
            status,
          };
          if (this.videoList.length) {
            if (!prompt) {
              this.$message.warning('请添加视频AI提示词')
              return
            }
						params.movieUrl = this.videoList[0].url
						params.movieThumbnailUrl = movieThumbnailUrl
						params.moviePrice =  moviePrice * 100
          }
          
          // price 提交到后端是分
          if (this.data.id) {
            this.updateSubmit({ uuid: this.data.id, ...params });
          } else {
            this.addSubmit(params);
          }
        } else {
          return false;
        }
      });
    },
    // 新增
    addSubmit(params) {
      addTemplate(params).then((res) => {
        this.$emit("refresh");
        this.$modal.msgSuccess("成功");
        this.data.bSwitch = false;
      });
    },
    // 修改
    updateSubmit(params) {
      updateTemplate(params).then((res) => {
        this.$emit("refresh");
        this.$modal.msgSuccess("成功");
        this.data.bSwitch = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.demo-ruleForm {
  width: 90%;
}

::v-deep .el-input-number .el-input__inner {
  text-align: left; /* 将文本对齐方式改为左对齐，这样数字就不会居中了 */
}
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 180px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 180px;
  height: 100px;
  display: block;
}

::v-deep .el-upload--picture-card {
  line-height: 98px;
  height: 100px;
  width: 180px;
  background-color: transparent;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  height: 100px;
  width: 180px;
}
</style>